<template>
  <div style="margin: 10px">
    <el-row :gutter="30" type="flex" justify="center">
      <el-col :span="20" class="text-center">
        <el-card class="sign-info">
          <h3>PDF盖章</h3>

          <div style="display: flex;justify-content: space-evenly;">
            <div style="display: flex; justify-content: start;  text-align: center;margin-left: 15px;">
              <div class="field">
                <div class="file">
                  <el-upload
                    id="pdf"
                    ref="upload"
                    accept=".pdf"
                    class="file-input"
                    action=""
                    :before-upload="handlePreview"
                    :show-file-list="false"
                  >
                    <el-button slot="trigger" size="small" type="primary">选取文件</el-button>
                    <div slot="tip" class="el-upload__tip">只能上传pdf文件</div>
                  </el-upload>
                  <span id="pdfName" />
                  <span id="pdfSize" />
                  <span id="pagesText" />
                </div>

              </div>
              <div class="field" />

              <el-upload
                id="file_input"
                ref="upload2"
                :disabled="disabledFileSignarea"
                class="file-input"
                action=""
                :before-upload="signareaChange"
                :show-file-list="false"
              >
                <el-button slot="trigger" size="small" type="primary">选取盖章文件</el-button>
                <div slot="tip" class="el-upload__tip">只能上传png/jpg文件</div>
              </el-upload>

              <div class="field" />
              <el-button size="small" type="primary" @click="submitOver()">提交盖章</el-button>
            </div>
          </div>
          <section id="print">
            <div id="imgDiv" />
            <div id="card" v-drag class="signarea card" />
          </section>
        </el-card>
      </el-col>
    </el-row>
    <br>
  </div>
</template>

<script>
import PDFJS from 'pdfjs-dist'
import { signatureSave } from '@/api/tool/signature'
import { getToken } from '@/utils/auth'

export default {
  name: 'Index',
  directives: {
    drag: {
      // 指令的定义
      bind: function(el, binding, vnode) {
        const _this = vnode.context

        // 获取当前元素
        const oDiv = el
        el.onmousedown = (e) => {
          // 算出鼠标相对元素的位置
          const disX = e.clientX - oDiv.offsetLeft
          const disY = e.clientY - oDiv.offsetTop

          document.onmousemove = (e) => {
            // 用鼠标的位置减去鼠标相对元素的位置，得到元素的位置
            const left = e.clientX - disX
            const top = e.clientY - disY

            if (left <= 10 || top <= 10 || left >= 850 || top >= 960) {
              // 追踪
              console.log('=========错误=========')
              console.log(left)
              console.log(top)
              console.log('X:' + disX)
              console.log('Y:' + disY)
              console.log('超出了')
              console.log('=======错误===========')
              // 追踪
              return
            }

            oDiv.style.left = left + 'px'
            oDiv.style.top = top + 'px'
            // 追踪
            _this.left = left
            _this.top = top

            console.log(_this.left, _this.top)
          }

          document.onmouseup = () => {
            document.onmousemove = null
            document.onmouseup = null
          }
        }
      }
    }
  },
  data() {
    return {
      left: 0,
      top: 0,
      width: 43,
      height: 43,
      // 存储pdf和印章
      fileList: [],
      upload: {
        headers: { 'Authorization': 'Bearer ' + getToken() }, // 设置上传的请求头部
        url: process.env.VUE_APP_BASE_API + '/signature/signature'// 上传的地址
      },
      // 章
      disabledFileSignarea: true
    }
  },
  watch: {},
  created() {
  },
  methods: {

    submitUpload() {
      this.$refs.upload.submit()
    },
    handleRemove(file, fileList) {
      console.log(file, fileList)
    },
    handleShow(file) {
      console.log(file)
    },
    handlePreview(file) {
      console.log(file)
      const pdf = document.getElementById('pdf')
      const imgDiv = document.getElementById('imgDiv')
      const ths = this
      pdf.onchange = () => {
        ths.fileList[0] = file
        ths.disabledFileSignarea = false
        // 清空上一PDF文件展示图
        imgDiv.innerHTML = ''
        const fileSize = file.size
        let mb
        if (fileSize) {
          mb = fileSize / 1048576
          if (mb > 50) {
            this.msgError('文件大小不能>50M!')
            return
          }
        }
        /* pdf.js无法直接打开本地文件,所以利用FileReader转换*/
        const reader = new FileReader()
        reader.readAsArrayBuffer(file)
        reader.onload = (e) => {
          const typedarray = new Uint8Array(e.target.result)
          PDFJS.cMapPacked = true
          // PDF转换为canvas
          PDFJS.getDocument(typedarray).then((pdf) => {
            // 清除文本、边框
            imgDiv.style.border = '0'

            if (pdf) {
              window.pageNum = pdf.numPages
              document.getElementById('pagesText').innerText = `共 ${window.pageNum} 页`
              for (let i = 1; i <= window.pageNum; i++) {
                const canvas = document.createElement('canvas')
                canvas.id = 'pageNum' + i
                // 追加pdf画面
                imgDiv.appendChild(canvas)
                const context = canvas.getContext('2d')
                openPage(pdf, i, context)
              }
            }
          })
        }
      }

      function openPage(pdfFile, pageNumber, context) {
        const scale = 2
        pdfFile.getPage(pageNumber).then((page) => {
          const viewport = page.getViewport(scale) // reference canvas via context
          const canvas = context.canvas
          canvas.width = viewport.width
          // $("#print").attr("style", "width:"+canvas.width+"px")
          canvas.height = viewport.height
          // 记录当前canvas的width，height
          window.wi = canvas.width
          window.he = canvas.height
          canvas.style.width = '100%'
          canvas.style.height = '100%'
          const renderContext = {
            canvasContext: context,
            viewport: viewport
          }
          page.render(renderContext)
        })
      }
    },
    // 公章相关：载入
    signareaChange(file) {
      if (!/image\/\w+/.test(file.type)) {
        this.msgError('文件必须为图片!')
        return false
      }
      this.fileList[1] = file
      const reader = new FileReader()
      reader.readAsDataURL(file)
      reader.onload = (e) => {
        document.querySelector('.signarea').innerHTML = `<img style="user-focus:none;pointer-events: none;width: 43mm;" src="${e.target.result}" alt=""/>`
      }
    },
    // 提交
    submitOver() {
      // 组装数据
      const formData = new FormData()
      formData.append('files', this.fileList[0])
      formData.append('files', this.fileList[1])
      formData.append('left', this.left)
      formData.append('top', this.top)
      formData.append('imgWidth', 125)
      formData.append('imgHeight', 125)
      signatureSave(formData).then(res => {
        console.log(res.msg)
      })
    }
  }
}

</script>

<style scoped>

::selection {
  background-color: transparent;
}

.theinput {
  position: fixed;
  z-index: 101;
}

.field {
  display: inline-block;
  margin-left: 15px;
}

#print {
  position: relative;
  margin: 0 auto;
  z-index: 1;
  width: 794px;
}

.signarea {
  position: absolute;
  z-index: 100;
  top: 0;
  left: 300px;
}

.signarea img {
  width: 43mm !important;
}

canvas {
  margin: 0;
  padding: 0;
  margin-bottom: -6px;
}

.zoom,
.tdeg,
.tview {
  position: absolute;
  cursor: pointer;
  background-color: #fff;
  padding: 3px 10px;
  border-radius: 4px;
}

.zoom {
  top: 0;
  left: -30px;
}

.del {
  top: 0;
  right: -30px;
}

.tview {
  left: -30px;
  bottom: 0;
}

.theinput {
  width: 300px;
  margin: 10px;
}
</style>
